import sys
import asyncio
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget

# 定义协程任务（模拟耗时操作）
async def background_task():
    print("任务开始")
    await asyncio.sleep(3)  # 模拟IO等待
    print("任务结束")
    return "结果数据"

# 工作线程类，用于运行协程事件循环
class WorkerThread(QThread):
    result_ready = pyqtSignal(str)  # 信号用于传递结果

    def run(self):
        # 在子线程中创建事件循环
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        # 创建并运行协程任务
        task = loop.create_task(background_task())
        
        # 监听任务完成
        task.add_done_callback(lambda t: loop.call_soon_threadsafe(
            self.result_ready.emit, t.result())
        )
        
        # 启动事件循环
        loop.run_forever()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        
    def init_ui(self):
        self.label = QLabel("等待任务...", self)
        self.button = QPushButton("启动任务", self)
        self.button.clicked.connect(self.start_task)
        
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.button)
        
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
        self.show()
    
    def start_task(self):
        self.thread = WorkerThread()
        self.thread.result_ready.connect(self.on_result)
        self.thread.start()
    
    def on_result(self, result):
        self.label.setText(f"任务结果: {result}")
        self.thread.quit()  # 任务完成后退出线程

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())